﻿/*
 * Copyright (C) 2016 江门市力德科技有限公司 版权所有
 *
 * File Name：    AppService.cs
 *
 * Description：  公司员工管理
 * 
 * Author：       陈超
 * 
 * Create Date：  2016-08-7  
 *
 * History：      2016-08-07  陈超    增加了添加，编辑，修改功能
 *                
*/

using CompanyManageSystem.Model;
using DevExpress.XtraTreeList.Nodes;
using EntityFramework.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using System.Windows.Forms;

namespace CompanyManageSystem.Service
{
    /// <summary>
    /// 公司管理
    /// </summary>
    public class AppService
    {
        #region 属性
        /// <summary>
        /// 数据仓库
        /// </summary>
        private PSContext _db;
        #endregion

        #region 构造方法
        /// <summary>
        /// 构造方法
        /// </summary>
        public AppService()
        {
            _db = new PSContext();
        }
        #endregion

        #region 公司
        /// <summary>
        /// 获取公司所有程序集
        /// </summary>
        /// <returns></returns>
        public List<Company> GetCompanys()
        {
            try
            {
                return _db.Companys.OrderBy(p => p.Code).ToList();
            }
            catch (Exception ex)
            {
                throw ex.InnerException;
            }
        }

        /// <summary>
        /// 添加公司
        /// </summary>
        /// <returns></returns>
        public Company AddCompany(Guid? parentID,string name,string code, bool isEnabled)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("公司名称必须填");
            Company com = new Company
            {
                ID = Guid.NewGuid(),
                CName = name,
                Code = code,
                IsEnabled = isEnabled,
                ParentID = parentID,
                CreateTime = DateTime.Now,
            };
            _db.Companys.Add(com);
            _db.SaveChanges();
            return com;
        }

        /// <summary>
        /// 编辑公司
        /// </summary>
        /// <param name="applicationID"></param>
        /// <param name="name"></param>
        /// <param name="isEnabled"></param>
        /// <returns></returns>
        public Company UpdateCompany(Guid? companyID, string name,string code, bool isEnabled)
        {
            var com = _db.Companys.Find(companyID);
            if (com != null)
            {
                com.CName = name;
                com.Code = code;
                com.IsEnabled = isEnabled;
                _db.SaveChanges();
                return com;
            }
            else
            {
                throw new Exception("该公司不存在!");
            }
        }

        /// <summary>
        /// 删除公司
        /// </summary>
        /// <param name="applicationID"></param>
        public void DelCompany(Guid companyID,TreeListNode node)
        {
            //检测指示范围的所有操作都已完成
            using (TransactionScope transaction = new TransactionScope())
            {
                //删除公司
                var com = _db.Companys.FirstOrDefault(p => p.ID == companyID);
                _db.Companys.Attach(com);
                _db.Companys.Remove(com);

                //删除部门
                var dept = _db.Departments.Where(p => p.CompanyID == companyID);
                _db.Departments.RemoveRange(dept);

                //删除员工(必须写不然数据库不会删除)
                var info = _db.CompanyStaffInfos.Where(p => p.CompanyID == companyID);
                _db.CompanyStaffInfos.RemoveRange(info);

                _db.SaveChanges();

                DelCompanyNodes(node);
                transaction.Complete();
            }
        }
        public void DelCompanyNodes(TreeListNode node)
        {
            for (var i = 0; i < node.Nodes.Count; i++)
            {
                var id = node.Nodes[i].GetValue("ID");
                var company = _db.Companys.Find(id);
                var dept = _db.Departments.Where(p => p.CompanyID == (Guid)id);
                var staff = _db.CompanyStaffInfos.Where(p => p.CompanyID == (Guid)id);
                _db.Companys.Remove(company);
                _db.Departments.RemoveRange(dept);
                _db.CompanyStaffInfos.RemoveRange(staff);
                _db.SaveChanges();
                DelCompanyNodes(node.Nodes[i]);
            }
        }

        /// <summary>
        /// 通过公司ID获取公司
        /// </summary>
        /// <param name="applicationID"></param>
        /// <returns></returns>
        public Company GetCompanyByID(Guid? applicationID)
        {
            return _db.Companys.ToList().Where(p => p.ID == applicationID).FirstOrDefault();
        }
        #endregion

        #region 员工
        /// <summary>
        /// 获取员工所有程序集
        /// </summary>
        /// <returns></returns>
        public List<CompanyStaffInfo> GetCompanyStaffInfo()
        {
            return _db.CompanyStaffInfos.ToList();
        }

        /// <summary>
        /// 通过公司ID获取对应员工
        /// </summary>
        /// <param name="applicationID"></param>
        /// <returns></returns>
        public List<CompanyStaffInfo> GetStaffsByCompanyID(Guid companyID)
        {
            return _db.CompanyStaffInfos.Where(p => p.CompanyID == companyID).OrderBy(p => p.FName).ToList();
        }

        /// <summary>
        /// 通过部门ID获取员工
        /// </summary>
        /// <param name="deptID"></param>
        /// <returns></returns>
        public List<CompanyStaffInfo> GetStaffByDeptID(Guid deptID)
        {
            return _db.CompanyStaffInfos.Where(p => p.DepartmentID == deptID).OrderBy(p => p.EnterTime).ToList();
        }

        /// <summary>
        /// 通过员工ID获取对应员工
        /// </summary>
        /// <param name="staffID"></param>
        /// <returns></returns>
        public CompanyStaffInfo GetStaffByID(Guid staffID)
        {
            return _db.CompanyStaffInfos.Where(p => p.ID == staffID).FirstOrDefault();
        }

        /// <summary>
        /// 获取所有省份
        /// </summary>
        /// <returns></returns>
        public List<Province> GetAllProvinces()
        {
            return _db.Provinces.OrderBy(p => p.Name).ToList();
        }

        /// <summary>
        /// 根据省份ID获取省份
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public string GetProvinceByID(Guid id)
        {
            return _db.Provinces.Where(p => p.ID == id).Select(p => p.Name).FirstOrDefault();
        }

        /// <summary>
        /// 根据ID更新员工
        /// </summary>
        /// <param name="id"></param>
        /// <param name="provinceID"></param>
        /// <returns></returns>
        public CompanyStaffInfo UpdateStaffByID(Guid id, Guid provinceID)
        {
            CompanyStaffInfo info = _db.CompanyStaffInfos.Where(p => p.ID == id).FirstOrDefault();
            info.ProvinceID = provinceID;
            info.Province = GetProvinceByID(provinceID);
            _db.SaveChanges();

            return info;
        }

        /// <summary>
        /// 获取所有毕业院校
        /// </summary>
        /// <returns></returns>
        public List<Graduation> GetAllGraduation()
        {
            return _db.Graduations.ToList();
        }

        /// <summary>
        /// 添加员工
        /// </summary>
        /// <param name="companyID"></param>
        /// <param name="name"></param>
        /// <param name="post"></param>
        /// <param name="wage"></param>
        /// <returns></returns>
        public CompanyStaffInfo AddStaff(Guid companyID,Guid deptID, string name, string code,string post, string wage, Guid provinceID, string graduation)
        {
            if (string.IsNullOrEmpty(name))
            {
                //throw new ArgumentNullException("姓名不能为空");
                MessageBox.Show("姓名不能为空!","温馨提示");
                return null;
            }

            CompanyStaffInfo info = new CompanyStaffInfo
            {
                ID = Guid.NewGuid(),
                FName = name,
                Code = code,
                Post = post,
                Wage = wage,
                CompanyID = companyID,
                EnterTime = DateTime.Now,
                ProvinceID = provinceID,
                Province = GetProvinceByID(provinceID),
                Graduation = graduation,
                DepartmentID = deptID,
            };
            _db.CompanyStaffInfos.Add(info);
            _db.SaveChanges();
            return info;
        }

        /// <summary>
        /// 编辑员工
        /// </summary>
        /// <returns></returns>
        public CompanyStaffInfo UpdateStaff(Guid staffID, string name,string code, string post, string wage, Guid provinceID, string graduation)
        {
            var info = _db.CompanyStaffInfos.Where(p => p.ID == staffID).FirstOrDefault();
            if (info == null)
            {
                //throw new Exception("该员工不存在");
                return null;
            }
            if (string.IsNullOrEmpty(name))
            {
                return null;
            }

            info.FName = name;
            info.Code = code;
            info.Post = post;
            info.Wage = wage;
            info.ProvinceID = provinceID;
            info.Province = GetProvinceByID(provinceID);
            info.Graduation = graduation;

            _db.SaveChanges();
            return info;
        }

        /// <summary>
        /// 删除员工
        /// </summary>
        /// <param name="staffID"></param>
        public void DelStaff(Guid staffID)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                var info = _db.CompanyStaffInfos.Where(p => p.ID == staffID).FirstOrDefault();
                _db.CompanyStaffInfos.Attach(info);
                _db.CompanyStaffInfos.Remove(info);
                _db.SaveChanges();

                transaction.Complete();
            }
        }

        /// <summary>
        /// 根据勾选删除员工
        /// </summary>
        public int DelStaffByChecked(Guid deptID,Guid[] staffID)
        {
            return _db.CompanyStaffInfos.Where(p => p.DepartmentID == deptID && staffID.Contains(p.ID)).Delete();
        }
        #endregion

        #region 用户
        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public List<Users> GetUsers()
        {
            return _db.Users.OrderBy(u => u.UName).ToList();
        }

        /// <summary>
        /// 通过ID获取用户
        /// </summary>
        /// <returns></returns>
        public Users GetUserByID(Guid userID)
        {
            return _db.Users.Where(p => p.ID == userID).FirstOrDefault();
        }

        /// <summary>
        /// 通过部门ID获取用户
        /// </summary>
        /// <param name="departmentID"></param>
        /// <returns></returns>
        public List<Users> GetUserByDepartmentID(Guid departmentID)
        {
            return _db.Users.Where(p => p.DepartmentID == departmentID).ToList();
        }

        /// <summary>
        /// 通过特定列的值获取用户
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public List<Users> GetUsersByShowText(string text)
        {
            return _db.Users.Where(p => p.UName.Contains(text) || p.TrueName.Contains(text)).ToList();
        }

        /// <summary>
        /// 通过部门ID获取用户
        /// </summary>
        /// <returns></returns>
        public List<Users> GetUsersByDeparment(Guid deparmentID)
        {
            return _db.Users.Where(u => u.DepartmentID == deparmentID).ToList();
        }

        /// <summary>
        /// 添加用户(不根据部门)
        /// </summary>
        /// <returns></returns>
        public Users AddUser(string uName, Guid departmentID, string trueName, bool isEnabled)
        {
            if (string.IsNullOrEmpty(uName) || string.IsNullOrEmpty(trueName))
            {
                MessageBox.Show("用户名和姓名不能为空!");
            }

            Users user = new Users
            {
                ID = Guid.NewGuid(),
                UName = uName,
                DepartmentID = departmentID,
                TrueName = trueName,
                IsEnabled = isEnabled,
                EnterTime = DateTime.Now,
            };
            _db.Users.Add(user);
            _db.SaveChanges();
            return user;
        }

        /// <summary>
        /// 编辑用户
        /// </summary>
        /// <returns></returns>
        public Users UpdateUsers(Guid userID, string uName, string trueName, bool IsEnabled)
        {
            var user = _db.Users.Where(p => p.ID == userID).FirstOrDefault();
            if (user == null)
            {
                MessageBox.Show("该用户不存在!");
            }

            if (string.IsNullOrEmpty(trueName) || string.IsNullOrEmpty(uName))
            {
                MessageBox.Show("用户名和姓名不能为空!");
            }
            user.ID = userID;
            user.UName = uName;
            user.TrueName = trueName;
            user.IsEnabled = IsEnabled;

            _db.SaveChanges();
            return user;
        }

        /// <summary>
        /// 删除用户(根据用户ID)
        /// </summary>
        public void DelUser(Guid userID)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                var user = _db.Users.Where(p => p.ID == userID).FirstOrDefault();
                _db.Users.Attach(user);
                _db.Users.Remove(user);
                _db.SaveChanges();

                transaction.Complete();
            }
        }
        #endregion

        #region 部门
        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public List<Department> GetDepartments()
        {
            return _db.Departments.ToList();
        }

        /// <summary>
        /// 根据ID获取部门
        /// </summary>
        /// <returns></returns>
        public Department GetDeptByID(Guid? deptid)
        {
            var dept = _db.Departments.Where(p => p.ID == deptid).FirstOrDefault();
            return dept;
        }

        /// <summary>
        /// 根据公司ID获取部门
        /// </summary>
        /// <param name="companyID"></param>
        /// <returns></returns>
        public List<Department> GetDeptByCompanyID(Guid companyID)
        {
            return _db.Departments.Where(p => p.CompanyID == companyID).OrderBy(p => p.Code).ToList();
        }

        /// <summary>
        /// 根据ID获取部门名字
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public String GetDeptNameByID(Guid id)
        {
            return _db.Departments.Where(p => p.ID == id).Select(p => p.Name).FirstOrDefault();
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        /// <returns></returns>
        public Department AddDept(string name, Guid? parentID, string code,Guid? companyID)
        {
            Department dept = new Department
            {
                ID = Guid.NewGuid(),
                Name = name,
                ParentID = parentID,
                Code = code,
                CompanyID = companyID,
            };
            _db.Departments.Add(dept);
            _db.SaveChanges();
            return dept;
        }

        /// <summary>
        /// 编辑部门
        /// </summary>
        /// <param name="deptID"></param>
        /// <param name="name"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public Department UpdateDept(Guid? deptID, string name, string code)
        {
            var dept = _db.Departments.Where(p => p.ID == deptID).FirstOrDefault();
            dept.Name = name;
            dept.Code = code;
            _db.SaveChanges();
            return dept;
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        public void DelDept(Guid deptID, TreeListNode node)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                //删除焦点部门
                var dept = _db.Departments.Where(p => p.ID == deptID).FirstOrDefault();
                //_db.Departments.Attach(dept);
                _db.Departments.Remove(dept);

                //删除焦点部门的用户
                var staff = _db.CompanyStaffInfos.Where(p => p.DepartmentID == deptID).ToList();
                _db.CompanyStaffInfos.RemoveRange(staff);
                _db.SaveChanges();

                //删除焦点部门的子部门和子部门包含的用户
                DelDeptNodes(node);

                transaction.Complete();
            }

        }
        public void DelDeptNodes(TreeListNode node)
        {
            for (var i = 0; i < node.Nodes.Count; i++)
            {
                var id = node.Nodes[i].GetValue("ID");
                var dept = _db.Departments.Where(p => p.ID == (Guid)id).FirstOrDefault();
                var staff = _db.CompanyStaffInfos.Where(p => p.DepartmentID == (Guid)id).ToList();
                _db.Departments.Remove(dept);
                _db.CompanyStaffInfos.RemoveRange(staff);
                _db.SaveChanges();
                DelDeptNodes(node.Nodes[i]);
            }
        }
        #endregion

        #region 登录
        public List<Login> GetAllLogin()
        {
            return _db.Logins.ToList();
        }

        /// <summary>
        /// 根据用户名和密码判断是否能登录
        /// </summary>
        /// <returns></returns>
        public bool LoginByNameAndPass(string userName, string password)
        {
            bool isExits = true;

            //查看是否有一行里面的数据同时满足这两个条件
            isExits = _db.Logins.Any(p => p.UserName == userName && p.Password == password);

            if (isExits)
            {
                return isExits;
            }
            else
            {
                return isExits;
            }
        }

        /// <summary>
        /// 根据用户名和密码获取ID
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Guid GetIDByNameAndPass(string userName, string password)
        {
            var id = _db.Logins.Where(p => p.UserName == userName && p.Password == password).Select(p => p.ID).FirstOrDefault();
            return id;
        }

        /// <summary>
        /// 根据ID获取密码
        /// </summary>
        /// <returns></returns>
        public string GetPasswordByID(Guid id)
        {
            var pass = _db.Logins.Where(p => p.ID == id).Select(p => p.Password).FirstOrDefault();
            return pass;
        }

        /// <summary>
        /// 编辑密码
        /// </summary>
        /// <param name="id"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Login UpdatePassword(Guid id, string password)
        {
            var login = _db.Logins.Where(p => p.ID == id).FirstOrDefault();
            login.Password = password;
            _db.SaveChanges();
            return login;
        }

        #endregion

        #region 管理员
        /// <summary>
        /// 获取所有管理员
        /// </summary>
        /// <returns></returns>
        public List<Manager> GetManagers()
        {
            return _db.Mangers.OrderBy(p => p.Name).ToList();
        }

        /// <summary>
        /// 根据ID获取管理员
        /// </summary>
        /// <param name="managerID"></param>
        /// <returns></returns>
        public Manager GetManagerByID(Guid managerID)
        {
            return _db.Mangers.Where(p => p.ID == managerID).FirstOrDefault();
        }

        /// <summary>
        /// 根据ID找到图片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public byte[] GetPhotoByID(Guid id)
        {
            var phtot = _db.Mangers.Where(p => p.ID == id).Select(p => p.Photo).FirstOrDefault();
            return phtot;
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="name"></param>
        /// <param name="password"></param>
        /// <param name="photoByte"></param>
        /// <returns></returns>
        public Manager AddManager(string name, string password, byte[] photoByte)
        {
            Manager manager = new Manager
            {
                ID = Guid.NewGuid(),
                Name = name,
                Password = password,
                Photo = photoByte,
            };
            _db.Mangers.Add(manager);
            //_db.SaveChanges();
            return manager;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <returns></returns>
        public Manager UpdateManager(Guid id, string name, string password, byte[] photoByte)
        {
            var man = _db.Mangers.Where(p => p.ID == id).FirstOrDefault();
            if (man == null)
            {
                MessageBox.Show("该管理员不存在!");
            }
            man.ID = id;
            man.Name = name;
            man.Password = password;
            man.Photo = photoByte;
            _db.SaveChanges();
            return man;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        public void DelManager(Guid id)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                var man = _db.Mangers.Where(p => p.ID == id).FirstOrDefault();
                _db.Mangers.Attach(man);
                _db.Mangers.Remove(man);
                _db.SaveChanges();

                transaction.Complete();
            }
        }
        #endregion

        #region 微信公众号管理
        /// <summary>
        /// 获取AccessToken列中的所用数据
        /// </summary>
        /// <returns></returns>
        public List<string> GetTokenInAToken()
        {
            return _db.ATokens.Select(p => p.AccessToken).ToList();
        }

        /// <summary>
        /// 根据ID查找公众号，并修改Access_Token信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AToken UpdateTokenByID(string id, string access_Token)
        {
            AToken info = _db.ATokens.Where(p => p.ID == new Guid(id)).FirstOrDefault();
            info.AccessToken = access_Token;
            _db.SaveChanges();
            MessageBox.Show("保存成功!");
            Console.WriteLine(access_Token);
            return info;
        }

        /// <summary>
        /// 获取ID列中所有ID
        /// </summary>
        /// <returns></returns>
        public List<Guid> GetIDInAToken()
        {
            return _db.ATokens.Select(p => p.ID).ToList();
        }

        /// <summary>
        /// 获取AppID列中的所有数据
        /// </summary>
        /// <returns></returns>
        public List<string> GetAppIDInAToken()
        {
            return _db.ATokens.Select(p => p.AppID).ToList();
        }

        /// <summary>
        /// 获取AppSecret中所有数据
        /// </summary>
        /// <returns></returns>
        public List<string> GetAppSecretInAToken()
        {
            return _db.ATokens.Select(p => p.AppSecret).ToList();
        }

        /// <summary>
        /// 获取所有群发的微信信息
        /// </summary>
        /// <returns></returns>
        public List<WeiXinInfo> GetAllWeiXinInfo()
        {
            return _db.WeiXinInfos.ToList();
        }

        /// <summary>
        /// 根据管理员ID获取群发的信息
        /// </summary>
        /// <param name="managerID"></param>
        /// <returns></returns>
        public List<WeiXinInfo> GetWeiXinInfoByManagerID(Guid managerID)
        {
            return _db.WeiXinInfos.Where(p => p.ManagerID == managerID).ToList();
        }

        /// <summary>
        /// 添加微信群发信息(也就是进行微信群发信息)
        /// </summary>
        /// <param name="managerID"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public WeiXinInfo AddWeiXinInfo(Guid managerID, string manager, string info)
        {
            if (string.IsNullOrEmpty(info))
            {
                MessageBox.Show("输入内容不能为空!");
            }
            WeiXinInfo weixin = new WeiXinInfo
            {
                ID = Guid.NewGuid(),
                ManagerID = managerID,
                ManagerName = manager,
                Info = info,
                SendTime = DateTime.Now,
            };
            _db.WeiXinInfos.Add(weixin);
            _db.SaveChanges();
            return weixin;
        }

        /// <summary>
        /// 删除所有微信信息
        /// </summary>
        /// <param name="managerID"></param>
        public void DelWeiXin(Guid managerID)
        {
            using (TransactionScope transaction = new TransactionScope())
            {
                var info = _db.WeiXinInfos.Where(p => p.ManagerID == managerID).ToList();
                //_db.WeiXinInfos.Attach(info);
                _db.WeiXinInfos.RemoveRange(info);
                _db.SaveChanges();

                transaction.Complete();
                MessageBox.Show("清除成功!");
            }

        }

        #endregion

        #region 数据库保存
        public void DataSave()
        {
            _db.SaveChanges();
        }
        #endregion

        public List<CompanyStaffInfo> GetStallInPage(int num, int pageNum)
        {
            var data = new List<CompanyStaffInfo>();

            data = _db.CompanyStaffInfos.OrderBy(p => p.Code).Skip(num).Take(pageNum).ToList();
            return data;
        }

    }
}
